import App from './App'

import {
  createSSRApp
} from 'vue'
import * as Pinia from 'pinia';
import {
  createPersistedState
} from 'pinia-plugin-persistedstate'
import {
  useUserStore
} from '@/store/index'

// 在 main.js 或 app.vue 中设置全局拦截器
uni.addInterceptor('request', {
  // 响应拦截
  success: (res) => {
    // console.log('on request: ', res)
    if (res.statusCode === 403) {
      console.log("statusCode: ", res.statusCode)
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/login/login', // 替换为你的登录页路径
      });

      return;
    }
    return res; // 必须返回 res，否则请求结果会被拦截
  },
});

// 适配uni-app的Storage
const uniStorage = {
  getItem(key) {
    return uni.getStorageSync(key)
  },
  setItem(key, value) {
    uni.setStorageSync(key, value)
  },
  removeItem(key) {
    uni.removeStorageSync(key)
  }
}

export function createApp() {
  const app = createSSRApp(App)

  const pinia = Pinia.createPinia()
  pinia.use(createPersistedState({
    storage: uniStorage, // 指定为uni-app的存储
    serialize: JSON.stringify, // 序列化处理
    deserialize: JSON.parse
  }))

  app.use(pinia);

  const userStore = useUserStore(); // 获取 store 的实例。
  userStore.initUserData(); // 调用初始化方法。

  app.config.globalProperties.$adpid = "1111111111"
  app.config.globalProperties.$backgroundAudioData = {
    playing: false,
    playTime: 0,
    formatedPlayTime: '00:00:00'
  }
  return {
    app,
    Pinia // 此处必须将 Pinia 返回
  }
}